<?php
/**
 * Created by PhpStorm.
 * User: JieHuiLong <jiehuilong@icloud.com>
 * Date: 2017/3/20
 * Time: 21:18
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AdminUser as User;
use App\Models\Domainame;
use DB, Cache;
use Illuminate\Http\Request;

class DomainameController extends Controller
{
    protected $fields = [
        'uid' => 1,
        'username' => '',
        'domain' => '',
        'ischeck' => 0,
        'check_type' => 2,
        'created_at' => 0,
        'updated_at' => 0,
    ];

    public function __construct(Request $request)
    {
        $this->uid = auth()->user()->id;
        $this->Domainame = new Domainame();
    }

    /**
     *域名小助手
     * 检测域名（Url）
     * @param array $domains 要检测的域名（Url）数组
     * @return 成功时返回，其他返回null
     */
    protected function checkDomain($domains)
    {
        $appId = 855043; //AppId
        $key = 'f7c1cee86e757221b78664034b0dfb78'; //密钥

        $timestamp = time();
        // $sign = md5($appId . $domains . $timestamp . $key);

        $sign = md5($appId . implode('', $domains) . $timestamp . $key);

        //按顺序拼接字符串并通过md5加密得到sign

        $json = array(
            'appid' => $appId,
            'timestamp' => $timestamp,
            'sign' => $sign,
            'list' => $domains,
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'http://trace.dodourl.com/dc/api/check');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json)); //直接将encode出来的json字符串Post到接口上
        $data = curl_exec($ch);
        curl_close($ch);

        if ($data == null) {
            return null;
        }

        return json_decode($data);
    }

    //微信域名列表
    protected function getDomainList($status = [1, -1])
    {

        if ($this->uid === 1) {
            $data = Domainame::whereIn('status', $status)->where('ischeck', 0)->where('check_type', '<>', 0)->select('id', 'uid', "domain", "status")
                ->orderBy('uid')->limit(1)->get();
        } else {
            $data = Domainame::whereIn('status', $status)->where('uid', $this->uid)->where('ischeck', 0)
                ->where('check_type', '<>', 0)->select('id', 'uid', "domain", "status")->limit(1)->get();
        }
        return $data;
    }

    public function checkall(Request $request)
    {
        $objThis = new Domainame();

        $tempId = "161985";
        $data['looptime'] = 10;
        if ($this->uid === 1) $data['looptime'] = 2;
        $data['playMusic'] = false;
        //$status =  [-1, -2] => GetQQ域名列表 ; $status =  [1, -1] => GetWechat域名列表 ;
        $data['lists'] = $objThis->getDomainList([1, -1]);
        //微信QQ检测
        if ($request->type === "QICQ") {
            //QQ检测
            $data['looptime'] = 10;
            $lists = Domainame::getQqLists();
            $checkList = Domainame::checkList([1, 0]);
            if ($checkList === false) {
                return redirect('/admin/domainame')->withErrors('请您先添加域名！');
            }
            if (count($checkList) === 0) $checkList = Domainame::checkList();
            $res = CheckDomainInQQ($checkList);
            foreach ($res as $keyCheck => $objCheck) {
                if ($objCheck['status'] == 0) {
                    $twoCheck = CheckDomainInQQ(array($objCheck['domain']));
                    $twoCheck[0]['content'] = e($twoCheck[0]['content']);
                    if ($twoCheck[0]['status'] == 0) {
                        foreach ($lists as $keyList => $objList) {
                            if ($objCheck['domain'] === $objList->domain) {
                                //如果微信也屏蔽了，status => -2 反之 设置为-1
                                if ($objList->status === 0) {
                                    Domainame::where('id', $objList->id)->update(['status' => -2,'qq_check_res' => $twoCheck[0]['content']]);
                                } else {
                                    Domainame::where('id', $objList->id)->update(['status' => -1,'qq_check_res' => $twoCheck[0]['content']]);
                                }
                                //SMS通知
                                $data['mobile'] = config('app.debug') ? "13694236191" : User::getMobile($objList->uid);
                                if (preg_match("/^1[34578]\d{9}$/", auth()->user()->mobile)) {
                                    sendSMS($data['mobile'], array($objList->domain, date('H'), date('i')), "165551");
                                }
                                break;
                            }
                        }
                        $data['playMusic'] = true;
                    } else {
                        break;
                    }

                }
            }
            $data['mobile'] = User::getMobile($this->uid);
            $data['checkType'] = $request->type;
            //总数
            if ($this->uid === 1) {
                $data['domainCount'] = Domainame::count();
                $checkListWaitCount = Domainame::whereIn('status', [1, 0])->where('ischeckqq', 0)->where('check_type', '<>', 0)->count();
            } else {
                $data['domainCount'] = Domainame::where('uid', $this->uid)->count();
                $checkListWaitCount = Domainame::where('uid', $this->uid)->whereIn('status', [1, 0])->where('ischeckqq', 0)->where('check_type', '<>', 0)->count();
            }
            //检测域名
            $ids = array_keys($checkList->toArray());
            if (!empty($ids)) Domainame::whereIn('id', $ids)->update(['ischeckqq' => 1]);

            //正常
            $data['whiteListCount'] = count($checkList);
            //屏蔽
            $data['blackList'] = $objThis->getBlackList([-1, -2]);

        } else {
            //微信检测
            if (count($data['lists']) === 0) {
                Domainame::where('ischeck', 1)->update(['ischeck' => 0]);
                $data['lists'] = $this->getDomainList();
            }
            $api = "http://vip.weixin139.com/weixin/wx_domain.php?user=1092506064&key=27ffb6b196ddcaa245bbcfc3ff05282f&domain=";
            $data['checkType'] = "wechat";
            if (count($data['lists']) !== 0) {
                foreach ($data['lists'] as $key => $obj) {
                    //微信检测
                    $res = $this->curlCkeck($api . $obj->domain);

                    /* if (isset($res['lasttime']) || !isset($res['errmsg']) || !isset($res['count']) || !isset($res['domain'])) {
                        sleep(10);//重新开始
                        return redirect("/admin/domainame/checkall");
                    } */
                    if ($res['status'] === null) {
                        $res1 = $this->checkDomain([$obj->domain]);
                        $res1 = $res1->list;
                        $domainStatus = $res1[0]->status;
                        switch ($domainStatus) {
                            case 0:
                                sendSMS('13694236191', array("接口异常", date('H'), date('i')), $tempId);
                                return redirect('/admin/domainame')->withErrors('太多人查询了，我“压力山大”，忙不过来了，您先去叹杯茶，先休息会再回来吧！ ');
                                break;
                            case 1:
                                $res['status'] = 0;
                                break;
                            case -1:
                                $res['status'] = 2;
                                break;
                            case -101:
                                sendSMS('13694236191', array("检测次数超出限制", date('H'), date('i')), $tempId);
                                return redirect('/admin/domainame')->withErrors('太多人查询了，我“压力山大”，忙不过来了，您先去叹杯茶，先休息会再回来吧！ ');
                                break;
                            case -102:
                                sendSMS('13694236191', array("余额不足", date('H'), date('i')), $tempId);
                                return redirect('/admin/domainame')->withErrors('太多人查询了，我“压力山大”，忙不过来了，您先去叹杯茶，先休息会再回来吧！ ');
                                break;
                            case -109:
                                return redirect('/admin/domainame')->withErrors('你的域名格式识别无效，请您检查');
                                break;
                            default:
                                # code...
                                break;
                        }
                    }
                    $data['res'] = $res;
                    if (empty($res)) {
                       /*  for ($i = 0; $i < 99999; $i++) {
                        } */
                        return redirect("/admin/domainame/checkall");
                    }
//                    $data['mobile'] = User::getMobile($obj->uid);
                    $data['mobile'] = config('app.debug') ? "13694236191" : User::getMobile($obj->uid);
                    //判断是否被拦截
					
                    if ($res['status'] == 2) {
                        if ($obj->status === -1) {
                            Domainame::where('id', $obj->id)->update(['status' => -2, 'ischeck' => 0]);
                        } else {
                            Domainame::where('id', $obj->id)->update(['status' => 0, 'ischeck' => 0]);
                        }

                        //SMS通知
                        if (preg_match("/^1[34578]\d{9}$/", auth()->user()->mobile)) {
                            sendSMS($data['mobile'], array($obj->domain, date('H'), date('i')), $tempId);
                        }

                        $data['looptime'] = 3;
                        $data['playMusic'] = true;
                    }
                    Domainame::where('id', $obj->id)->update(['ischeck' => 1, 'updated_atwx' => date('Y-m-d H:i:s')]);
                    $status = [1, -1];
                    if ($this->uid === 1) {
                        //总数
                        $data['domainCount'] = Domainame::count();
                        //正常
                        $data['whiteListCount'] = Domainame::whereIn('status', $status)->count();
                        $checkListWaitCount = Domainame::whereIn('status', $status)->where('ischeck', 0)->where('check_type', '<>', 0)->select('id', 'uid', "domain", "status")
                            ->where('check_type', '<>', 0)->count();
                    } else {
                        //总数
                        $data['domainCount'] = Domainame::where('uid', $this->uid)->count();
                        //正常
                        $data['whiteListCount'] = Domainame::where('uid', $this->uid)->whereIn('status', $status)->count();
                        $checkListWaitCount = Domainame::whereIn('status', $status)->where('uid', $this->uid)->where('ischeck', 0)->where('check_type', '<>', 0)->select('id', 'uid', "domain", "status")
                            ->where('check_type', '<>', 0)->count();

                    }
                    //屏蔽
                    $data['blackList'] = $objThis->getBlackList([0, -2]);
                }
            } else {
                //return redirect('/admin/domainame');
                return redirect('/admin/domainame')->withErrors('请您先添加域名！');
            }
        }
        $status = [1, -1];
        if ($checkListWaitCount === 0) {
            Domainame::where('ischeck', 1)->update(['ischeck' => 0]);
            if ($this->uid === 1) {
                $checkListWaitCount = Domainame::whereIn('status', $status)->where('ischeck', 0)->where('check_type', '<>', 0)->select('id', 'uid', "domain", "status")
                    ->where('check_type', '<>', 0)->count();
            } else {
                $checkListWaitCount = Domainame::whereIn('status', $status)->where('uid', $this->uid)->where('ischeck', 0)->where('check_type', '<>', 0)->select('id', 'uid', "domain", "status")
                    ->where('check_type', '<>', 0)->count();
            }

        }
        $data['checkListWaitCount'] = $checkListWaitCount;
        return view('admin.domainame.check', $data);
    }

    public function curlCkeck($weixin_url)
    {
        $timeout = 3;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $weixin_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $arr = json_decode($result, true);
        return $arr;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //var_dump(curl("https://new.tmall.com/?wh_weex=true&wh_isabtest=true&ali_trackid=2:mm_26141145_20470766_69724572:1490149439_3k7_236979185"));
        if ($request->ajax()) {
            $data = array();
            $data['draw'] = $request->get('draw');
            $start = $request->get('start');
            $length = $request->get('length');
            $order = $request->get('order');
            $columns = $request->get('columns');
            $search = $request->get('search');
            $data['recordsTotal'] = Domainame::where(session('authAdminCondition'))->count();
            if (strlen($search['value']) > 0) {
                $data['recordsFiltered'] = Domainame::where(function ($query) use ($search) {
                    $query->where('domain', 'LIKE', '%' . $search['value'] . '%')
                        ->orWhere('username', 'like', '%' . $search['value'] . '%');
                })->where(session('authAdminCondition'))->count();

                $data['data'] = Domainame::where(function ($query) use ($search) {
                    $query->where('domain', 'LIKE', '%' . $search['value'] . '%')
                        ->orWhere('username', 'like', '%' . $search['value'] . '%');
                })->where(session('authAdminCondition'))
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            } else {
                $data['recordsFiltered'] = Domainame::where(session('authAdminCondition'))->count();
                $data['data'] = Domainame::where(session('authAdminCondition'))
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            }
            foreach ($data['data'] as $key => $obj) {
                if ($obj->status === -2) {
                    $str = "域名被封【QQ、微信】";
                } elseif ($obj->status === -1) {
                    $str = "域名被封【QQ】";
                } elseif ($obj->status === 0) {
                    $str = "域名被封【微信】";
                } else {
                    $str = "域名正常";
                }
                if ($obj->status === 1) {
                    $obj->status = '<span class="text-success">' . $str . '</span>';
                } else {
                    $obj->status = '<span class="text-danger">' . $str . '</span>';
                }
            }
            return response()->json($data);
        }
        return view('admin.domainame.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data = [];
        foreach ($this->fields as $field => $default) {
            $data[$field] = old($field, $default);
        }
        $data['userList'] = User::lists('name', 'id');
        return view('admin.domainame.create', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $objDomainame = new Domainame;
        foreach (array_keys($this->fields) as $field) {
//            $objDomainame->$field = $request->get($field);
            $newData[$field] = $request->get($field);
        }
        $domainArr = array_filter(preg_split('/\s+/', $request->domain));
        foreach ($domainArr as $key => $value) {
            $newData['domain'] = $value;
			$newData['updated_at'] = date('Y-m-d H:i:s');
            $id = $objDomainame->where('uid', $this->uid)->where('domain', $value)->value('id');
            if (!$id) $newItem[] = $newData;
        }
		
        if (!empty($newItem)) $objDomainame->insert($newItem);

        /*for ($n = 0; $n < 10; $n++) {
            DB::delete("delete from s_domainames  where id in (select id from (select  max(id) as id,count(domain) as count from s_domainames group by domain having count >1 order by count desc) as tab )");
        }*/

        return redirect('/admin/domainame')->withSuccess('添加成功！');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id or string ids=>1,2,3,4,5,6
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if (is_numeric($id)) {
            $tag = Domainame::find((int)$id);
            if ($tag) {
                $tag->delete();
            } else {
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        } else {
            $idArr = explode(',', $id);
            $recordRow = Domainame::whereIn('id', $idArr)->delete();
            if (!$recordRow) {
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        }
        return redirect()->back()
            ->withSuccess("删除成功");
    }
}
